<template>
  <table class="room-name-json">
    <tr>
      <td style="width: 128px;">房型</td>
      <td>内容</td>
      <td></td>
    </tr>

    <tr v-for="(item, index) in list" :key="index">
      <td>
        <ElInput :model-value="item.name" @update:model-value="onChangeName($event, index)"/>
      </td>
      <td>
        <ElInput :model-value="item.content" @update:model-value="onChangeContent($event, index)" />
      </td>
      <td>
        <ElButton v-if="!index" link type="primary" @click="onAddItem">添加</ElButton>
        <ElButton v-if="index" link type="primary" @click="onRemoveItem(index)">删除</ElButton>
      </td>
    </tr>
  </table>
</template>

<script setup lang="ts">
import { ElButton, ElInput } from 'element-plus';
import { computed } from 'vue'
interface Props {
  modelValue: string;
  data: object;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  data: () => ({})
})

interface Emits {
  'update:model-value': [string]
}
const emit = defineEmits<Readonly<Emits>>()

const getObj = (v: string) => {
  let obj = {}
  try {
    obj = JSON.parse(v)
  } catch{}
  return obj
}

const list = computed({
  get() {
    const obj = props.modelValue ? getObj(props.modelValue ) : {}
    const list = []
    for (let key in obj) {
      list.push({ name: key, content: obj[key] })
    }
    return list.length ? list : [{ name: '', content: '' }]
  },
  set(val) {
    const v = val || []
    if (!v.length) return emit('update:model-value', '')
    if (v.length === 1 && !v[0].name && !v[0].content) return emit('update:model-value', '')
    const obj = {}
    v.forEach(item => {
      obj[item.name] = item.content
    })
    emit('update:model-value', JSON.stringify(obj))
  }
})

const onChangeName = (name, index) => {
  const l = [...list.value]
  l.splice(index, 1, { name, content: l[index].content })
  list.value = l
}

const onChangeContent = (content, index) => {
  const l = [...list.value]
  l.splice(index, 1, { name: l[index].name, content: content })
  list.value = l
}

const onAddItem = () => {
  const l = [...list.value]
  l.unshift({ name: '', content: '' })
  list.value = l
}

const onRemoveItem = index => {
  const l = [...list.value]
  l.splice(index, 1)
  list.value = l
}
</script>

<style scoped lang="scss">
.room-name-json {
  width: 100%;
  font-family: PingFangHK-Regular;
  font-weight: 400;
  font-size: 12px;
  color: #333333;
}
</style>
